<template>
    <el-drawer size="50%" v-model="drawer" :title="'添加旅行套餐'" direction="rtl" :before-close="closeDrawer">
        <el-form size="small" ref="formRef" style="max-width: 800px" :model="formData" status-icon :rules="rules"
            label-width="100px">
            <el-form-item label="套餐名称" prop="travelPackageName">
                <el-input v-model="formData.travelPackageName" style="width: 300px;" />
            </el-form-item>

            <el-form-item label="套餐描述" prop="description">
                <el-input type="textarea" v-model="formData.travelPackageDesc" style="width: 300px;" />
            </el-form-item>

            <el-form-item label="最大人数" prop="maxPeople">
                <el-input-number v-model="formData.maxPeople" :min="1" style="width: 300px;" />
            </el-form-item>

            <el-form-item label="套餐图片" prop="packageImages">
                <el-upload class="upload-demo" action="" :auto-upload="false" :on-change="handleChange"
                    :on-remove="handleRemove" :file-list="fileList" :multiple="true" :limit="5" list-type="picture-card"
                    accept="image/*">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #tip>
                        <div class="el-upload__tip">只能上传jpg/png文件，且不超过500KB</div>
                    </template>
                </el-upload>
            </el-form-item>

            <el-form-item label="套餐类型" prop="packageType">
                <el-input v-model="formData.travelPackageType" style="width: 300px;" />
            </el-form-item>
            <el-form-item label="套餐价格" prop="price">

                <el-input v-model="formData.price" style="width: 300px;" />
            </el-form-item>

            <el-form-item label="价格描述" prop="priceDesc">
                <el-input v-model="formData.priceDesc" type="textarea" :rows="2" style="width: 300px;"
                    placeholder="请输入价格描述，例如：含餐/不含餐，含门票等" />
            </el-form-item>

            <el-form-item label="初始地点" prop="initially">
                <el-input v-model="formData.initially" style="width: 300px;" placeholder="请输入行程出发地点" />
            </el-form-item>

            <el-form-item label="导游选择" prop="guideId">
                <el-select v-model="formData.guideId" style="width: 300px;">
                    <el-option v-for="guide in guides" :key="guide.id" :label="guide.guideName" :value="guide.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="出行时间" prop="travelDate">
                <el-date-picker v-model="formData.travelDate" type="datetimerange" range-separator="至"
                    start-placeholder="开始时间" end-placeholder="结束时间" style="width: 300px;" @change="handleDateChange" />
            </el-form-item>


            <template v-if="showHotelSelect">
                <el-form-item label="选择酒店" prop="region">
                    <div class="region-selectors">
                        <el-select v-model="formData.province" @change="fetchCities" placeholder="选择省">
                            <el-option v-for="province in provinces" :key="province.id" :label="province.name"
                                :value="province.area_id" />
                        </el-select>
                        <el-select v-model="formData.city" @change="fetchHotels" placeholder="选择市">
                            <el-option v-for="city in cities" :key="city.area_id" :label="city.name"
                                :disabled="!formData.province" :value="city.name" />
                        </el-select>
                        <el-select @change="handleHotelSelect(formData.hotelId)" v-model="formData.hotelId"
                            placeholder="选择酒店" style="width: 300px;">
                            <el-option v-for="hotel in hotels" :key="hotel.id" :label="hotel.hotelName"
                                :value="hotel.id" />
                        </el-select>
                        <template v-if="formData.hotelId">
                            <el-select v-model="formData.roomTypeId" style="width: 200px; margin-right: 10px"
                                placeholder="选择房型">
                                <el-option v-for="room in roomTypes" :key="room.id" :label="room.room_type"
                                    :value="room.id" :disabled="!roomAvailability.get(room.id)">
                                    <span>{{ room.room_type }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">
                                        剩余: {{ roomAvailability.get(room.id) || 0 }}
                                    </span>
                                </el-option>
                            </el-select>

                            <el-input-number v-if="formData.roomTypeId && roomAvailability.get(formData.roomTypeId)"
                                v-model="formData.roomNum" :min="1" :max="roomAvailability.get(formData.roomTypeId)"
                                style="width: 120px" />
                        </template>
                    </div>
                </el-form-item>

            </template>

            <el-form-item label="行程安排">
                <div v-for="(day, dayIndex) in formData.itinerary" :key="dayIndex" class="day-itinerary">
                    <div class="day-header">
                        <h3>第 {{ day.day }} 天 ({{ day.date }})</h3>
                        <el-button type="primary" size="small" @click="addItineraryItem(dayIndex)">添加行程</el-button>
                    </div>

                    <div v-for="(item, itemIndex) in day.items" :key="itemIndex" class="itinerary-item">
                        <el-time-picker v-model="item.startTime" placeholder="开始时间" :min-time="day.dayStart"
                            :max-time="day.dayEnd" format="HH:mm" style="width: 140px; margin-right: 10px" />
                        <el-time-picker v-model="item.endTime" placeholder="结束时间"
                            :min-time="item.startTime || day.dayStart" :max-time="day.dayEnd" format="HH:mm"
                            style="width: 140px; margin-right: 10px" />
                        <el-select v-model="item.type" style="width: 120px; margin-right: 10px">
                            <el-option label="住宿" value="hotel" :disabled="!formData.needHotel" />
                            <el-option label="景点" value="spot" />
                            <el-option label="其他" value="other" />
                        </el-select>

                        <template v-if="item.type === 'hotel'">
                            <el-select v-model="item.hotelId" style="width: 200px">
                                <el-option v-for="hotel in hotels" :key="hotel.id" :label="hotel.hotelName"
                                    :value="hotel.id" />
                            </el-select>
                        </template>

                        <template v-if="item.type === 'spot'">
                            <el-select v-model="item.spotId" style="width: 200px">
                                <el-option v-for="spot in spots" :key="spot.id" :label="spot.travelAttactionName"
                                    :value="spot.id" />
                            </el-select>
                        </template>

                        <template v-if="item.type === 'other'">
                            <el-input v-model="item.description" style="width: 200px" />
                        </template>

                        <el-button type="danger" @click="removeItineraryItem(dayIndex, itemIndex)"
                            style="margin-left: 10px">删除</el-button>
                    </div>
                </div>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(formRef)">添加</el-button>
                <el-button @click="resetForm(formRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import type { FormInstance, FormRules, UploadProps, UploadFile } from 'element-plus'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
import { $locationList, $fetchHotels, $loadGuides, $fetchRoomTypes, $fetchRoomAvailability, $savePackage, $loadSpots } from '../../api/travelAdmin'
// 表单数据
const formData = ref({
    travelPackageName: '',
    travelPackageDesc: '',
    maxPeople: 1,
    travelPackageType: '',
    guideId: '',
    travelDate: [],
    destination: [],
    hotelId: '',
    roomTypeId: '',
    roomNum: '',
    price: '', // 重置价格
    priceDesc: '', // 重置价格描述
    initially: '', // 重置初始地点
    itinerary: [],
    province: '',
    city: ''
})

// 文件上传相关
const fileList = ref<UploadFile[]>([])

const handleChange: UploadProps['onChange'] = async (file, fl) => {
  fileList.value=fl
};

const handleRemove: UploadProps['onRemove'] = (file) => {
    const index = fileList.value.indexOf(file)
    if (index > -1) {
        fileList.value.splice(index, 1)
    }
}

// 抽屉控制
const drawer = ref(false)
const closeDrawer = () => {
    drawer.value = false
    formRef.value?.resetFields()
    formData.value = {
        travelPackageName: '',
        travelPackageDesc: '',
        maxPeople: 1,
        travelPackageType: '',
        guideId: '',
        travelDate: [],
        destination: [],
        hotelId: '',
        roomTypeId: '',
        roomNum: '',
        price: '', // 重置价格
        priceDesc: '', // 重置价格描述
        initially: '', // 重置初始地点
        itinerary: [],
        province: '',
        city: ''
    }
}

// 表单相关
const formRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    // 添加验证规则
})

// 行程管理
const addItineraryItem = (dayIndex: number) => {
    formData.value.itinerary[dayIndex].items.push({
        startTime: null,
        endTime: null,
        type: 'other',
        description: '',
        hotelId: '',
        spotId: '',
    })
}

const removeItineraryItem = (dayIndex: number, itemIndex: number) => {
    formData.value.itinerary[dayIndex].items.splice(itemIndex, 1)
}


const provinces = ref([])
const cities = ref([])
const hotels = ref([])
const guides = ref([])
// 添加获取地区数据的方法
const fetchProvinces = async () => {
    // TODO: 调用API获取省份数据
    const response = await $locationList({ id: 0 })
    if (response.code === 2001) {
        provinces.value = response.data;

        cities.value = [];  // 清空区县数据
    } else {
        ElNotification({
            title: '获取省份信息失败',
            message: '请联系管理员',
            type: 'error',
        })
    }

}

const fetchCities = async (provinceId: string) => {
    selectedCity.value = '' // 清空已选择的城市
    formData.value.hotelId = '' // 清空已选择的酒店
    cities.value = [] // 清空城市列表
    hotels.value = [] // 清空酒店列表

    const response = await $locationList({ id: provinceId })
    if (response.code === 2001) {
        cities.value = response.data
    } else {
        ElNotification({
            title: '获取城市信息失败',
            message: '请联系管理员',
            type: 'error',
        })
    }
}

const fetchHotels = async (cityName: string) => {
    // TODO: 调用API获取酒店数据
    const response = await $fetchHotels({ cityName: cityName })
    if (response.code === 2001) {
        hotels.value = response.data;
    } else {
        ElNotification({
            title: '获取酒店信息失败',
            message: '请联系管理员',
            type: 'error',
        })
    }

}

const loadGuides = async () => {
    const response = await $loadGuides()
    if (response.code === 2001) {


        guides.value = response.data;
    } else {
        ElNotification({
            title: '获取导游信息失败',
            message: '请联系管理员',
            type: 'error',
        })
    }

}

const spots = ref([])
const loadSpots = async () => {
    const response = await $loadSpots()
    if (response.code === 2001) {
        spots.value = response.data

    } else {
        ElNotification({
            title: '获取景点信息失败',
            message: '请联系管理员',
            type: 'error',
        })
    }
}

// 计算属性：判断是否显示酒店选择
const showHotelSelect = computed(() => {
    if (!formData.value.travelDate || formData.value.travelDate.length !== 2) {
        return false
    }

    const startDate = new Date(formData.value.travelDate[0])
    const endDate = new Date(formData.value.travelDate[1])
    const daysDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24))

    // 如果行程超过1天且选择需要住宿，则显示酒店选择
    return daysDiff > 0 && formData.value.needHotel
})

// 暴露必要的属性和方法
defineExpose({
    drawer,
    formData
})



const roomTypes = ref([]) // 添加房型列表
const roomAvailability = ref(new Map()) // 存储房型可用数量
const selectedProvince = ref('')
const selectedCity = ref('')

// 添加获取房型的方法
const fetchRoomTypes = async (hotelId: string) => {
    roomTypes.value = [] // 清空房型列表
    roomAvailability.value.clear() // 清空可用数量

    if (!hotelId || !formData.value.travelDate || formData.value.travelDate.length !== 2) {
        return
    }

    try {
        // 1. 获取酒店所有房型
        const roomTypesRes = await $fetchRoomTypes({ hotelId })
        if (roomTypesRes.code === 2001) {
            roomTypes.value = roomTypesRes.data

            // 2. 获取每个房型的可用数量
            for (const room of roomTypes.value) {
                const availabilityRes = await $fetchRoomAvailability({
                    roomTypeId: room.id,
                    checkTime: formData.value.travelDate[0],
                    leaveTime: formData.value.travelDate[1]
                })

                if (availabilityRes.code === 2001) {
                    roomAvailability.value.set(room.id, availabilityRes.data)
                }
            }
        } else {
            ElNotification({
                title: '获取房型失败',
                message: '请联系管理员',
                type: 'error',
            })
        }
    } catch (error) {
        console.error('获取房型失败:', error)
    }
}

// 修改选择酒店的方法，选择酒店后自动获取房型
const handleHotelSelect = async (hotelId: string) => {
    if (hotelId) {
        await fetchRoomTypes(hotelId)
    }
}




// 修改 handleDateChange 函数
const handleDateChange = async (dates: [Date, Date] | null) => {
    if (!dates || dates.length !== 2) {
        formData.value.needHotel = false
        formData.value.itinerary = []
        return
    }

    const startDate = new Date(dates[0])
    const endDate = new Date(dates[1])
    const daysDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24))

    // 如果超过一天，询问是否需要住宿
    if (daysDiff > 0) {
        try {
            await ElMessageBox.confirm(
                '您的行程超过一天，是否需要安排住宿？',
                '提示',
                {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'info',
                }
            )
            formData.value.needHotel = true
        } catch {
            formData.value.needHotel = false
        }
    } else {
        formData.value.needHotel = false
        formData.value.hotelId = ''
    }

    // 生成每天的行程安排
    formData.value.itinerary = []
    for (let i = 0; i <= daysDiff; i++) {
        const currentDate = new Date(startDate)
        currentDate.setDate(startDate.getDate() + i)

        // 设置当天的开始和结束时间限制
        const dayStart = new Date(currentDate)
        dayStart.setHours(0, 0, 0, 0)
        const dayEnd = new Date(currentDate)
        dayEnd.setHours(23, 59, 59, 999)

        formData.value.itinerary.push({
            day: i + 1,
            date: currentDate.toISOString().split('T')[0],
            dayStart: dayStart,
            dayEnd: dayEnd,
            items: []
        })
    }
}


//提交表单

// 修改提交方法
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate(async (valid) => {
        if (valid) {
            try {
                // 构造提交数据
                const formDataToSubmit = new FormData()


                // 格式化日期时间的函数
                const formatDateTime = (date: Date) => {
                    const year = date.getFullYear()
                    const month = String(date.getMonth() + 1).padStart(2, '0')
                    const day = String(date.getDate()).padStart(2, '0')
                    const hours = String(date.getHours()).padStart(2, '0')
                    const minutes = String(date.getMinutes()).padStart(2, '0')
                    const seconds = String(date.getSeconds()).padStart(2, '0')
                    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
                }

                // 添加基本信息
                const packageDetail = {
                    travelPackageName: formData.value.travelPackageName,
                    travelPackageDesc: formData.value.travelPackageDesc,
                    maxPeople: formData.value.maxPeople,
                    travelPackageType: formData.value.travelPackageType,
                    guideId: formData.value.guideId,
                    hotelId: formData.value.hotelId,
                    roomTypeId: formData.value.roomTypeId,
                    roomNum: formData.value.roomNum,
                    price: formData.value.price,
                    priceDesc: formData.value.priceDesc,
                    initially: formData.value.initially,
                    // 转换日期格式
                    travelDate: formatDateTime(new Date(formData.value.travelDate[0])),
                    overDate: formatDateTime(new Date(formData.value.travelDate[1])),
                    // 构造行程数据
                    trips: formData.value.itinerary.flatMap(day =>
                        day.items.map(item => {
                            // 处理时间字符串
                            const startTimeStr = typeof item.startTime === 'string'
                                ? item.startTime
                                : item.startTime.toTimeString().slice(0, 8)
                            const endTimeStr = typeof item.endTime === 'string'
                                ? item.endTime
                                : item.endTime.toTimeString().slice(0, 8)

                            // 组合日期和时间
                            const startDateTime = new Date(`${day.date} ${startTimeStr}`)
                            const endDateTime = new Date(`${day.date} ${endTimeStr}`)

                            return {
                                startDate: formatDateTime(startDateTime),
                                endDate: formatDateTime(endDateTime),
                                activeDesc: item.type === 'other' ? item.description : '',
                                travelAttractionId: item.type === 'spot' ? item.spotId : 0,
                                hotelId: item.type === 'hotel' ? item.hotelId : 0
                            }
                        })
                    )
                }
                console.log(packageDetail);


                // 添加表单数据
                formDataToSubmit.append('travelPackageDetail', JSON.stringify(packageDetail))

                if (fileList.value.length == 0) {
                    ElNotification({
                        title: '失败',
                        message: '请选择要上传的图片',
                        type: 'error'
                    })
                    return
                }

                // 添加图片文件
                fileList.value.forEach(file => {
                    console.log(file.raw);
                    if(file.raw){
                        formDataToSubmit.append('TravelPackagePhoto', file.raw)
                    }
                    
                })

                console.log(fileList.value);


                // 发送请求
                const response = await $savePackage(formDataToSubmit)

                if (response.code === 2001) {
                    ElNotification({
                        title: '成功',
                        message: '套餐添加成功',
                        type: 'success'
                    })
                    closeDrawer()
                } else {
                    throw new Error(response.message)
                }
            } catch (error) {
                ElNotification({
                    title: '错误',
                    message: error.message || '套餐添加失败',
                    type: 'error'
                })
            }
        } else {
            ElNotification({
                title: '错误',
                message: '请填写完整所有必填项',
                type: 'warning'
            })
        }
    })
}

onMounted(() => {
    fetchProvinces();
    loadGuides();
    loadSpots()

})


</script>

<style scoped>
.itinerary-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
}
</style>